//
//  PredicateTableViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/7/25.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit
class PredicateTableViewController: BaseTableViewController,UITextFieldDelegate {

    let pickerField = UITextField()
    
    var feeList: Array<JSON> = []
    
    weak var delegate: CreateProjectViewController?
    
    var _source: [JSON] = []
    
    let picker = YearPicker.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 220)))
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        if years.count > 0 {
            yearLabel.text = years[0]
        }
        
        picker.years = years.map({ (str) -> Int in
            return Int(Double.init(str) ?? 0)
        })
        
        configPicker()
        
        let view = UIView()
        view.backgroundColor = .dftBack
        view.frame = CGRect.init(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 10))
        self.tableView.tableHeaderView = view
        
        self.tableView.register(UINib.init(nibName: "ApprovalDetailCell", bundle: Bundle.main), forCellReuseIdentifier: "ApprovalDetailCell")
        self.tableView.register(UINib.init(nibName: "PredicateInfoCell", bundle: Bundle.main), forCellReuseIdentifier: "PredicateInfoCell")
        self.tableView.reloadData()
    }
    
    @objc override func canceledit()->Void{
        self.view.endEditing(true)
    }
    
    @objc override func endedit()->Void{
        super.endedit()
        let index = self.picker.datePicker.selectedRow(inComponent: 0)
        if index > -1 && index < years.count {
            yearLabel.text = String(picker.selectedYear)
        } else {
            yearLabel.text = "合计"
        }
        
        self.tableView.reloadData()
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {

    }
    
    func configPicker() -> Void {
        
        self.view.addSubview(pickerField)
        pickerField.inputView = picker
        pickerField.delegate = self
        pickerField.inputAccessoryView = self.toolbarview
    }
    
    @objc func cancelAction(){
        self.pickerField.resignFirstResponder()
    }
    
    
    @objc func sureAction(){
        yearLabel.text = String(self.picker.selectedYear)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    
    @objc func showDetail(btn: UIButton)->Void{
        detail(index: btn.tag - 1000)
    }
    
    func detail(index: Int)->Void{
        
        let dest = PurchaseItemDetailViewController()
        
        dest.currentindex = index
        
        dest.feeList = self.feeList
        
        dest.title = "采购项明细"
        
        self.push(destination: dest)
        
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 55
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if self.ifwithamount {
            return 55
        } else {
            if let content = self.showedshource[indexPath.row].first?.value {
                
                if content.count > 0{
                    
                    let size = content.size(with: UIFont.systemFont(ofSize: 15), maxSize: CGSize.init(width: tableView.width - 32, height: 1000000))
                    
                    return 55 + size.height
                    
                } else {
                    
                    return 65
                    
                }
            } else {
                return 65
            }
        }
    }

    
    let yearLabel = UILabel()
    var years: [String] = []
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView()
        v.backgroundColor = UIColor.white
        v.frame = CGRect.init(origin: .zero, size: CGSize.init(width: self.view.width, height: 55))
        let name = UILabel()
        name.text = "年份"
        name.font = UIFont.boldSystemFont(ofSize: 16)
        name.textColor = .hex("333333")
        let size = name.text!.size(with: name.font)
        name.frame = CGRect.init(origin: CGPoint.init(x: 15, y: v.height / 2 - size.height / 2), size: size)
        v.addSubview(name)
        let selecteddateidx = (picker.datePicker.selectedRow(inComponent: 0)>0 ? picker.datePicker.selectedRow(inComponent: 0) : 0)
        if selecteddateidx < years.count {
            yearLabel.text = years[selecteddateidx]
        }
        yearLabel.textColor = .hex("999999")
        yearLabel.font = UIFont.systemFont(ofSize: 14)
        name.textColor = .hex("333333")
        if yearLabel.text != nil {
            let size1 = yearLabel.text!.size(with: yearLabel.font)
            yearLabel.frame = CGRect.init(origin: CGPoint.init(x: name.left + name.width + 30, y: v.height / 2 - size1.height / 2), size: size1)
        }
        v.addSubview(yearLabel)
        let imageView = UIImageView()
        imageView.image = UIImage(named: "icon_jump")
        imageView.size = CGSize(width: 12, height: 14)
        imageView.origin = CGPoint.init(x: self.view.width - 26, y: 16.5)
        v.addSubview(imageView)
        let button = UIButton.init(type: .custom)
        button.frame = v.bounds
        button.addTarget(self, action: #selector(shows), for: .touchUpInside)
        v.addSubview(button)
        let line = UIView()
        line.backgroundColor  = tableView.separatorColor
        line.frame = CGRect.init(origin: CGPoint.init(x: 15, y: 54.5), size: CGSize.init(width: self.view.width - 15, height: 0.5))
        v.addSubview(line)
        return v
    }
    
    @objc func shows()->Void{
        pickerField.becomeFirstResponder()
    }
    
    var ifwithamount = false    //判断是否包含预算执行数据
    var showedshource: [Dictionary<String,String?>] {
        get{
            if ifwithamount == false {
                var array: [Dictionary<String,String?>] = []
                let selectindex = self.picker.datePicker.selectedRow(inComponent: 0)
                if selectindex > -1 && selectindex < self.years.count {
                    let items = _source.filter { (json) -> Bool in
                        return String(json.contents?["year"]?.int ?? 0) == self.yearLabel.text
                    }
                    if items.count > 0 {
                        let item = items[0]
                        let projEstimatedRevenue = item.contents?["projEstimatedRevenue"]?.int ?? 0
                        array.append(["预计合同签订金额(元):": String(projEstimatedRevenue / 100).rmbformat])
                        let contractPredict = item.contents?["contractPredict"]?.int ?? 0
                        array.append(["预计合同收入(元):": String(contractPredict / 100).rmbformat])
                        array.append(["预计本年开票金额(元):": String((item.contents?["invoicePredict"]?.int ?? 0) / 100).rmbformat])
                        array.append(["成本合计(元):": String((item.contents?["projEstimatedCost"]?.int ?? 0) / 100).rmbformat])
                        array.append(["人工成本(元):": String((item.contents?["laborCost"]?.int ?? 0) / 100).rmbformat])
                        array.append(["人员外包(元):": String((item.contents?["staffoutCostLabor"]?.int ?? 0) / 100).rmbformat])
                        array.append(["劳务外包(元):": String((item.contents?["outsourcingCostLabor"]?.int ?? 0) / 100).rmbformat])
                        array.append(["服务(元):": String((item.contents?["outsourcingCostBusiness"]?.int ?? 0) / 100).rmbformat])
                        array.append(["工程(元):": String((item.contents?["engineerSubCost"]?.int ?? 0) / 100).rmbformat])
                        array.append(["物资(元):": String((item.contents?["materialExpense"]?.int ?? 0) / 100).rmbformat])
                        array.append(["差旅(元):": String((item.contents?["travelExpense"]?.int ?? 0) / 100).rmbformat])
                        array.append(["商务(元):": String((item.contents?["businessExpense"]?.int ?? 0) / 100).rmbformat])
                        array.append(["会务(元):": String((item.contents?["meetingExpense"]?.int ?? 0) / 100).rmbformat])
                        array.append(["租赁(元):": String((item.contents?["rent"]?.int ?? 0) / 100).rmbformat])
                        array.append(["低值易耗品(元):": String((item.contents?["suppliesExpense"]?.int ?? 0) / 100).rmbformat])
                        array.append(["其他(元):": String((item.contents?["otherCost"]?.int ?? 0) / 100).rmbformat])
                        return array
                    }
                    return []
                } else {
                    //total
                    var totalarrs: [JSON] = []
                    for item in self.years {
                        let items = _source.filter { (json) -> Bool in
                            return String(json.contents?["year"]?.int ?? 0) == item
                        }
                        totalarrs.append(contentsOf: items)
                    }
                    //获取到了所有的数据
                    var result:[Dictionary<String,String?>] = []
                    let projEstimatedRevenue = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["projEstimatedRevenue"]?.int ?? 0)
                    }//item.contents?["projEstimatedRevenue"]?.int ?? 0
                    result.append(["预计合同签订金额(元):": String(projEstimatedRevenue / 100).rmbformat])
                    let contractPredict = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["contractPredict"]?.int ?? 0)
                    }
                    result.append(["预计合同收入(元):": String(contractPredict / 100).rmbformat])
                    
                    let ticketing = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["invoicePredict"]?.int ?? 0)
                    }
                    array.append(["预计本年开票金额(元):": String(ticketing / 100).rmbformat])
                    
                    let costs = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["projEstimatedCost"]?.int ?? 0)
                    }
                    array.append(["成本合计(元):": String(costs / 100).rmbformat])
                    
                    let laborCost = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["laborCost"]?.int ?? 0)
                    }
                    array.append(["人工成本(元):": String(laborCost / 100)])
                    
                    let staffoutCostLabor = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["staffoutCostLabor"]?.int ?? 0)
                    }
                    array.append(["人员外包(元):": String(staffoutCostLabor / 100).rmbformat])
                    
                    let outsourcingCostLabor = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["outsourcingCostLabor"]?.int ?? 0)
                    }
                    array.append(["劳务外包(元):": String(outsourcingCostLabor / 100).rmbformat])
                    let outsourcingCostBusiness = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["outsourcingCostBusiness"]?.int ?? 0)
                    }
                    array.append(["服务(元):": String(outsourcingCostBusiness / 100).rmbformat])
                    
                    let engineerSubCost = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["engineerSubCost"]?.int ?? 0)
                    }
                    array.append(["工程(元):": String(engineerSubCost / 100).rmbformat])
                    
                    let materialExpense = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["materialExpense"]?.int ?? 0)
                    }
                    
                    array.append(["物资(元):": String(materialExpense / 100).rmbformat])
                    
                    let travelExpense = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["travelExpense"]?.int ?? 0)
                    }
                    array.append(["差旅(元):": String(travelExpense / 100).rmbformat])
                    
                    let businessExpense = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["businessExpense"]?.int ?? 0)
                    }
                    array.append(["商务(元):": String(businessExpense / 100).rmbformat])
                    
                    let meetingExpense = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["meetingExpense"]?.int ?? 0)
                    }
                    array.append(["会务(元):": String(meetingExpense / 100).rmbformat])
                    let rent = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["rent"]?.int ?? 0)
                    }
                    array.append(["租赁(元):": String(rent / 100).rmbformat])
                    let suppliesExpense = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["suppliesExpense"]?.int ?? 0)
                    }
                    array.append(["低值易耗品(元):": String(suppliesExpense / 100).rmbformat])
                    let otherCost = totalarrs.reduce(0) { (result, json) -> Int in
                        return result + (json.contents?["otherCost"]?.int ?? 0)
                    }
                    array.append(["其他(元):": String(otherCost / 100).rmbformat])
                    return array
                }
            }
            return []
        }
    }
    
    //0 19年预算 1 19年执行 2 20年预算 3 20年执行
    var amountsource: [JSON]{
        let selectindex = self.picker.datePicker.selectedRow(inComponent: 0)

        if selectindex < self.years.count {
            switch selectindex{
            case 0:
                return _source.map({ (json) -> JSON in
                    var dic: [String: Any] = [:]
                    let list = json["moneyList"].array ?? []
                    if list.count > 0 {
                        dic["yusuan"] = list[0].int ?? 0
                    } else {
                        dic["yusuan"] = 0
                    }
                    if list.count > 1 {
                        dic["zhixing"] = list[1].int ?? 0
                    } else {
                        dic["zhixing"] = 0
                    }
                    dic["name"] = json["name"].string ?? ""
                    return JSON(dic)
                })
            case 1:
                return _source.map({ (item) -> JSON in
                    var dic: [String: Any] = [:]
                    let list = item["moneyList"].array ?? []
                    if list.count > 2 {
                        dic["yusuan"] = list[2].int ?? 0
                    } else {
                        dic["yusuan"] = 0
                    }
                    if list.count > 3 {
                        dic["zhixing"] = list[3].int ?? 0
                    } else {
                        dic["zhixing"] = 0
                    }
                    dic["name"] = item["name"].string ?? ""
                    return JSON(dic)
                })
            default:
                break
            }
        } else {
            var sources: [JSON] = []
            for item in _source {
                var dic: [String: Any] = [:]
                let list = item["moneyList"].array ?? []
                if list.count > 3 {
                    dic["yusuan"] = (list[0].int ?? 0) + (list[2].int ?? 0)
                    dic["zhixing"] = (list[1].int ?? 0) + (list[3].int ?? 0)
                }
                dic["name"] = item["name"].string
                sources.append(JSON(dic))
            }
            return sources
        }
        return []
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if self.ifwithamount {
            let cell = tableView.dequeueReusableCell(withIdentifier: "PredicateInfoCell") as! PredicateInfoCell
            cell.model = self.amountsource[indexPath.row]
            if [6,7,8].contains(indexPath.row) {
                cell.accessoryType = .disclosureIndicator
            } else {
                cell.accessoryView = nil
                cell.accessoryType = .none
            }
            return cell
        } else {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "ApprovalDetailCell") as? ApprovalDetailCell {
                
                cell.titleLbl.text = self.showedshource[indexPath.row].keys.first
                cell.detailLbl.text = self.showedshource[indexPath.row].values.first ?? ""
                if [7,8,9].contains(indexPath.row) {
                    cell.accessoryType = .disclosureIndicator
                } else {
                    cell.accessoryType = .none
                }
                
                return cell
            }
        }
        
        return UITableViewCell()
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.ifwithamount {
            return self.amountsource.count
        } else {
            return self.showedshource.count
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.row == 0 {
            
            self.pickerField.becomeFirstResponder()
            
        } else {
            
            if self.ifwithamount {
                if [6,7,8].contains(indexPath.row) {
                    self.detail(index: indexPath.row - 6)
                }
            } else {
                if [7,8,9].contains(indexPath.row) {
                    self.detail(index: indexPath.row - 7)
                }
            }
            
        }
        
    }

}
